Kurt Hsu's blog

The Rails developer in taiwan.


  • 首頁

  • 標籤

  • 分類

  • 歸檔

[JavaScript]dataURL轉換Blob 並用 formdata上傳

發表於 2017-09-18 更新於 2019-08-28 分類於 JavaScript

繼上一篇[Vue2]使用vue-avatar-editor套件裁減照片做出大頭貼(Resize image),這次我要做的是用form-data把我的出圖傳上去,但裁剪後得出圖格式是dataURL,而要上傳的格式要是Blob,該如何實現呢?

注意事項:
1.有import jQuery
2.有import axios

dataURL to Blob

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
var imgURL = $('.someCanvas').toDataURL("image/png");
//直接複製國外的function
dataURItoBlob: function (dataURI) {
// convert base64 to raw binary data held in a string
// doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this
var byteString = atob(dataURI.split(',')[1]);

// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]

// write the bytes of the string to an ArrayBuffer
var ab = new ArrayBuffer(byteString.length);

// create a view into the buffer
var ia = new Uint8Array(ab);

// set the bytes of the buffer to the correct values
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}

// write the ArrayBuffer to a blob, and you're done
var blob = new Blob([ab], {type: mimeString});
return blob;

}
var imgBlob = this.dataURItoBlob(imgURL);
//到這邊我們已經製造好blob,開始製造formdata
var postData = new FormData();
postData.append('key', imgBlob, 'fileName.jpg' );
//最後一個參數是可以自行設定檔案名稱
axios.post('url', postData, {'content-type': 'multipart/form-data'})
.then( function (response) {
//handle succeed
}).catch(function (error) {
//handle error
})

這樣就能利用dataURL上傳Blob格式囉!

參考文件

image 各種型態轉換(blob, dataURL, canvas) in JavaScript

stackoverflow-Blob from DataURL?

stackoverflow-How to give a Blob uploaded as FormData a file name?

# formdata # JavaScript # dataURL # Blob
[JavaScript]Do not scroll parent element
Pakogi 第一次 meetup 講解 ETH wallet by Nic
  • 文章目錄
  • 本站概要

Kurt Hsu

Progress One Percent Every Day
171 文章
55 分類
163 標籤
RSS
  1. 1. dataURL to Blob
  2. 2. 參考文件
© 2020 Kurt Hsu
由 Hexo 強力驅動 v3.8.0
|
主題 – NexT.Muse v7.3.0